﻿#include<iostream>
#include<string>
#include<sstream>
using namespace std;
using std::string;
using std::stringstream;

typedef struct Role {
	string Id;
	int Exp;
} *PROLE;

//获取数据长度（数据字符串）
int GetDataCount(string str);

//获取当前角色Id
string GetIdStr(string str, int* istart, int* iend);

//获取当前角色Exp
string GetExpStr(string str, int* istart, int* iend);

//获取所有角色数据
void GetRole(string str, PROLE pRole, int icount);

//打印所有角色数据
void PrintRole(PROLE pRole, int icount);

//对角色数据进行排序
void sort(PROLE pRole, int icount);

int main() {
	string strData = "id=TomyClare;exp=9523;id=Sunny;exp=9523;id=DyBaby;exp=25301;id=Simple;exp=25301;id=Bkacs11;exp=2100;id=DumpX;exp=36520;";

	int icount{ GetDataCount(strData) };//得到角色数量

	PROLE pRole = new Role[icount];//根据角色数创建结构体数组

	GetRole(strData, pRole, icount);//获取所有角色数据

	sort(pRole, icount);//对角色数据进行排序

	PrintRole(pRole, icount);//打印所有角色数据

}

//因为每个角色都是有2个属性，所以查找所有属性数量除以2就是角色数
int GetDataCount(string str) {
	int icount{};
	for (int i = 0; i < str.length(); i++) {
		if (str[i] == ';') {
			icount++;
			i += 3;
		}
	}
	return icount / 2;
}

string GetIdStr(string str, int* istart, int* iend) {

	string strReturn{};
	(*istart) = str.find("id=", (*istart));
	if ((*istart) == std::string::npos)return strReturn;
	(*iend) = str.find(";", (*istart) + 3);
	strReturn = str.substr((*istart) + 3, (*iend) - (*istart) - 3);
	(*istart) = (*iend) + 1;
	return strReturn;

}

string GetExpStr(string str, int* istart, int* iend) {

	string strReturn{};
	(*istart) = str.find("exp=", (*istart));
	if ((*istart) == std::string::npos)return strReturn;
	(*iend) = str.find(";", (*istart) + 4);
	strReturn = str.substr((*istart) + 4, (*iend) - (*istart) - 4);
	(*istart) = (*iend) + 1;
	return strReturn;

}

void GetRole(string str, PROLE pRole, int icount) {

	int istart{}, iend{}, count{};//
	string flag;//用于判断返还的字符串是否为空

	do {

		flag = GetIdStr(str, &istart, &iend);
		if (flag.empty())break;
		pRole[count].Id = flag;
		flag.erase();
		pRole[count++].Exp = std::stoi(GetExpStr(str, &istart, &iend));

	} while (true);

}

void PrintRole(PROLE pRole, int icount) {
	for (int i = 0; i < icount; i++) {
		cout << pRole[i].Id << " " << pRole[i].Exp << endl;
	}
}

void sort(PROLE pRole, int icount) {
	for (int i = 1; i < icount; i++) {
		for (int y = 1; y < icount; y++) {
			if (pRole[y].Exp > pRole[y - 1].Exp) {
				Role tmp = pRole[y - 1];
				pRole[y - 1] = pRole[y];
				pRole[y] = tmp;
			}
		}
	}
}